package com.kwg.allinpay_demo

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import com.kwg.library.INTENT_PAY_RESULT_PARAMS
import com.kwg.library.RESULT_CODE_SUCCESS
import com.kwg.library.model.PayInfo
import com.kwg.library.model.PayResult
import com.kwg.library.ui.main.PrePayActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initListener()
    }

    private fun initListener() {
        btn_sumit.setOnClickListener {
            if (checkIllegal()) {
                Toast.makeText(baseContext, "请正确输入必填项", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            PrePayActivity.startActivity(this, PayInfo.Builder.newBuilder()
                                                            .withBizOrderNo(et_order_id.text.toString())
                                                            .withAmount(et_amount.text.toString().toDouble())
                                                            .withBizUserId(et_user_id.text.toString())
                                                            .withBizUserName(et_username.text.toString())
                                                            .withGoodsName(et_goods_name.text.toString())
                                                            .build())
        }

    }

    private fun checkIllegal(): Boolean {
        return TextUtils.isEmpty(et_order_id.text) || TextUtils.isEmpty(et_amount.text)
                || TextUtils.isEmpty(et_user_id.text) || TextUtils.isEmpty(et_username.text)
                || TextUtils.isEmpty(et_goods_name.text)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if(resultCode != RESULT_CODE_SUCCESS) {
            Toast.makeText(baseContext, "支付失败(${resultCode})", Toast.LENGTH_SHORT).show()
            return;
        }
        val result = data.getParcelableExtra<PayResult>(INTENT_PAY_RESULT_PARAMS)
        Toast.makeText(baseContext, "支付成功(${result?.showString()})", Toast.LENGTH_SHORT).show()

    }
}